﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Drawing;
using System.Threading;
using System.Data;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Diagnostics;


using ZhimeiSoft.Framework.Client.Base;
using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.Framework.Client.Utils;
using ZhimeiSoft.CharmManager.Client.Manager;
using ZhimeiSoft.CharmManager.Client.Interface;
using ZhimeiSoft.Framework.Client.Configuration;

namespace ZhimeiSoft.CharmManager.Client.Forms
{

    public class PhoneCallCtrl
    {
        private static PhoneCallCtrl StaticphoneCallCtrl;

        private System.Windows.Forms.Control parentForm;

        private PhoneCallCtrl(System.Windows.Forms.Control p)
        {
            this.parentForm = p;
        }

        public static PhoneCallCtrl getPhoneCallCtrl(System.Windows.Forms.Control aParentFrom)
        {
            if (StaticphoneCallCtrl == null)
            {
                StaticphoneCallCtrl = new PhoneCallCtrl(aParentFrom);
            }
            return StaticphoneCallCtrl;

        }
        public EventCallBack callBack;

        private byte[] m_btServerReceive = new byte[10240];
        private SerialPort serialPortPhone;
        private bool isStart = false;
        /// <summary>
        /// 猫接收来电的AT命令字符串
        /// </summary>
        //private string m_showPhoneCmd = "AT+VCID=1" + "\r" + "ATS0=2" + "\r"--接收
        private string m_showPhoneCmd = "AT+VCID=1\r | ATS0=0\r | AT+CLIP=1\r | AT+CLCC\r";// AT+CLCC\r";
        //private string m_showPhoneCmd = "AT+VCID=1" + "\r" + "at#cid=1" + "\r";--测试

        ClientConfiguration clientConfig;

        DataSet dsCustomInfo = new DataSet();

        public bool IsStartCall
        {
            get
            {
                return isStart;
            }
        }

        public void testShowWindow()
        {
            string error = string.Empty;
            if (BussinessProxyManager.Instance != null)
            {
                BussinessProxyManager.Instance.QueryCustomState(string.Empty, out dsCustomInfo, out error);
            }
            string aa = "DATE = 0527 \r\n TIME = 2250 \r\n NMBR = 18666130658";
            GetPhoneNumber(aa);
        }
        /// <summary>
        /// 初始化Modem的通讯端口
        /// </summary>
        public void InitPort()
        {
            string error = string.Empty;
            if (BussinessProxyManager.Instance != null)
            {
                BussinessProxyManager.Instance.QueryCustomState(string.Empty, out dsCustomInfo, out error);
            }
            if (serialPortPhone != null && serialPortPhone.IsOpen)
            {
                serialPortPhone.DataReceived -= new SerialDataReceivedEventHandler(serialPortPhone_DataReceived);
                serialPortPhone.DiscardInBuffer();
                serialPortPhone.DiscardOutBuffer();
                serialPortPhone.Close();
                serialPortPhone.Dispose();
            }

            clientConfig = new ClientConfiguration();
            m_btServerReceive = new byte[10240];
            serialPortPhone = new SerialPort(clientConfig.ComPort, 9600, Parity.None, 8, StopBits.One);
            serialPortPhone.DataReceived += new SerialDataReceivedEventHandler(serialPortPhone_DataReceived);
            serialPortPhone.ReadBufferSize = 10240;
            serialPortPhone.WriteBufferSize = 10240;
            m_showPhoneCmd = clientConfig.ComCommand;
            try
            {

                serialPortPhone.Open();
                serialPortPhone.DtrEnable = true;
                serialPortPhone.RtsEnable = true;
                isStart = true;
                serialPortPhone.Write("AT+VCID=1" + "\r" + "ATS0=0" + "\r");
                //serialPortPhone.Write(m_showPhoneCmd);
                /*string[] modemCommand = m_showPhoneCmd.Split('|');
                foreach (string command in modemCommand)
                {
                    //AppendLog("传入MODEM命令：" + command);
                    serialPortPhone.Write(command);//("AT+VCID=1" + "\r");
                }*/
            }
            catch (Exception ex)
            {
                isStart = false;
                MsgBox.MsgInfo("来电显示端口设置错误!\r\n" + ex.Message);
            }
            finally
            {

            }
        }
        /// <summary>
        /// 停止端口
        /// </summary>
        public void StopPort()
        {
            serialPortPhone.DataReceived -= new SerialDataReceivedEventHandler(serialPortPhone_DataReceived);
            serialPortPhone.DiscardInBuffer();
            serialPortPhone.DiscardOutBuffer();
            serialPortPhone.Close();
            isStart = false;
        }
        /// <summary>
        /// 串口接收数据的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPortPhone_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {

                SerialPort tmpSp = sender as SerialPort;

                string strServerReceive = tmpSp.ReadLine();
                if (strServerReceive.Trim().Equals(string.Empty))
                {
                    return;
                }

                byte[] m_btServerReceive111 = new byte[10240];
                tmpSp.Read(m_btServerReceive111, 0, m_btServerReceive111.Length);
                strServerReceive = UnicodeEncoding.ASCII.GetString(m_btServerReceive111);


                Debug.WriteLine("正在接受信息:" + strServerReceive);
                this.parentForm.Invoke(new MethodInvoker(delegate
                {
                    GetPhoneNumber(strServerReceive);
                }));
            }
            catch (Exception ex)
            {
                //debug 测试AT命令
                //AppendLog(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
        /// <summary>
        /// 抓取电话号码
        /// </summary>
        private void GetPhoneNumber(string strServerReceive)
        {
            //AppendLog("传入数据：\r" + m_strServerReceive);
            string[] NMBR = strServerReceive.Split("\r\n".ToCharArray());
            string showNbr = string.Empty;
            foreach (string nbr in NMBR)
            {
                if (nbr.IndexOf("NMBR") == -1)
                {
                    continue;
                }
                if (nbr.Split('=').Length >= 1)
                {
                    showNbr = nbr.Split('=')[1].Trim();
                    break;
                }
            }
            Debug.WriteLine("正在接受信息:" + showNbr);
            if (showNbr != string.Empty)
            {
                //Regex r = new Regex(@"NMBR\s=\s[0-9]*");
                string num = "";
                // Cycle through the matches //Match才接触
                //for (Match m = r.Match(strServerReceive); m.Success; m = m.NextMatch())
                //{
                //  num = m.Value;
                //}
                //去掉"NUMB = "前缀;
                num = showNbr;
                //如果是程控电话则去掉第一位(代表外线近来的电话一般是9)
                if (num.Length > 11)
                {
                    num = num.Substring(1);
                }
                //处理固话-默认固话为7位
                if (num.Length < 11 && num.Length > 7)
                {
                    num = num.Substring(num.Length - 7);
                }
                DataRow[] drPhoneNumber = dsCustomInfo.Tables[0].Select("CMOBILEPHONE = '" + num + "' OR CMOBILEPHONE = '" + num + "'"
                    );
                if (drPhoneNumber.Length == 0)
                {
                    //模糊查找电话
                    drPhoneNumber = dsCustomInfo.Tables[0].Select("CMOBILEPHONE LIKE '%" + num + "%' OR CMOBILEPHONE LIKE '%" + num + "%'");
                }

                StringBuilder sShowPhoneCall = new StringBuilder();
                string sNickName = "";
                string sCustomName = "";

                if (drPhoneNumber.Length != 0)
                {
                    sNickName = "会员昵称：" + drPhoneNumber[0][DBEntityCustomInfo.FieldName.CNICKNAME].ToString().PadRight(12, ' ');
                    sCustomName = "会员姓名：" + drPhoneNumber[0][DBEntityCustomInfo.FieldName.CNAME].ToString().PadRight(12, ' ');

                    sShowPhoneCall.AppendLine(sNickName);
                    sShowPhoneCall.AppendLine(sCustomName);
                }
                else
                {
                    //没有登记电话
                    sShowPhoneCall.Append("无法找到会员信息".PadLeft(12, ' ') + "\r\n" + "来电号码：" + num.ToString().PadRight(12, ' '));
                }
                DateTime phoneCallTime = new DateTime(DateTime.Now.Ticks);
                InfoPhoneCall phoneCallInfo = getInfoPhoneCall(drPhoneNumber, num, phoneCallTime);
                if (callBack != null)
                {
                    //回调写入
                    callBack(phoneCallInfo);
                }
                else { 
                    //自己记录
                    PhoneLog.SaveLog(phoneCallInfo);
                }
                Debug.WriteLine("正在接受信息：显示窗口。");
                string sTime = "来电时间：" + (DateTime.Now.Hour.ToString() + "点" + DateTime.Now.Minute.ToString() + "时" + DateTime.Now.Second.ToString() + "秒").PadRight(12, ' ');
                sShowPhoneCall.Append("\r\n");
                sShowPhoneCall.Append(sTime);

                Color backColor = Color.FromArgb(89, 135, 214);
                Color fontColor = Color.FromArgb(106, 0, 0);
                ShowNotifyWindow(Color.SteelBlue, "来电提醒", backColor, sShowPhoneCall.ToString(), fontColor, num);
            }
        }

        private InfoPhoneCall getInfoPhoneCall(DataRow[] drCustomDataRow, string phoneNumber, DateTime callTime)
        {
            InfoPhoneCall phoneCall = new InfoPhoneCall();
            if (drCustomDataRow.Length == 0)
            {
                phoneCall.CUSTOMERID = "-1";
                phoneCall.CUSTOMERNAME = "无会员信息";
                phoneCall.CUSTOMERNICKNAME = "无会员信息";
            }
            else
            {
                phoneCall.CUSTOMERID = drCustomDataRow[0][DBEntityCustomInfo.FieldName.CUSTOMERID].ToString();
                phoneCall.CUSTOMERNAME = drCustomDataRow[0][DBEntityCustomInfo.FieldName.CNAME].ToString();
                phoneCall.CUSTOMERNICKNAME = drCustomDataRow[0][DBEntityCustomInfo.FieldName.CNICKNAME].ToString();
            }

            phoneCall.CALLTIME = callTime.ToLongTimeString();
            phoneCall.PHONENBR = phoneNumber;

            return phoneCall;
        }

        /// <summary>
        /// 右下角来电提醒窗体
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="conent">内容</param>
        public void ShowNotifyWindow(Color backColor, string title, Color titleColor, string conent, Color textColor, string phoneID)
        {
            NotifyWindow phoneShow = new NotifyWindow(title, conent);
            //nw.TitleClicked += new System.EventHandler(titleClick);
            //nw.TextClicked += new System.EventHandler(textClick);
            phoneShow.WaitTime = 11000;  //设置来电提示窗体等待时间为24小时;
            phoneShow.TitleFont = new Font("微软雅黑", 12, FontStyle.Bold);
            phoneShow.TitleColor = titleColor;
            phoneShow.Font = new Font("微软雅黑", 14);
            phoneShow.TextColor = textColor;
            phoneShow.BackColor = backColor;
            phoneShow.SetDimensions(300, 200);
            phoneShow.Tag = phoneID;
            phoneShow.Notify();
        }
    }
    /// <summary>
    /// 保存来电的信息类
    /// </summary>
    public static class PhoneLog
    {
        static DataTable dsPhone;
        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <returns></returns>
        public static DataTable GetPhoneLogDataSet()
        {
            if (dsPhone == null)
            {
                dsPhone = InfoPhoneCall.GetPhoneDataTable();
            }
            else
            {
                return dsPhone;
            }
            string fileName = getPhoneFileName();

            if (!File.Exists(fileName))
            {
                dsPhone.WriteXmlSchema(fileName, true);
            }
            else
            {
                dsPhone.ReadXml(fileName);
            }
            return dsPhone;
        }
        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="infoPhone"></param>
        public static void SaveLog(InfoPhoneCall infoPhone)
        {
            dsPhone = GetPhoneLogDataSet();
            DataRow drNew = dsPhone.NewRow();
            drNew[InfoPhoneCall.FieldName.CUSTOMERID] = infoPhone.CUSTOMERID;
            drNew[InfoPhoneCall.FieldName.CUSTOMERNAME] = infoPhone.CUSTOMERNAME;
            drNew[InfoPhoneCall.FieldName.CUSTOMERNICKNAME] = infoPhone.CUSTOMERNICKNAME;
            drNew[InfoPhoneCall.FieldName.CALLTIME] = infoPhone.CALLTIME;
            drNew[InfoPhoneCall.FieldName.PHONENBR] = infoPhone.PHONENBR;
            dsPhone.Rows.Add(drNew);
            dsPhone.AcceptChanges();
            string fileName = getPhoneFileName();
            dsPhone.WriteXml(fileName, true);
        }

        /// <summary>
        /// 获取当天的数据集文件
        /// </summary>
        /// <returns></returns>
        private static string getPhoneFileName()
        {
            string fileDirectory = Application.StartupPath + "\\PhoneCall\\";
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }
            int nowTime = DateTime.Now.Year * 10000 + DateTime.Now.Month * 100 + DateTime.Now.Day;
            string fileName = fileDirectory + "PhoneCall" + nowTime + ".xml";
            return fileName;
        }
        
    }
}
